import { useState } from 'react'
import { useDebounceFn } from 'ahooks'

const HoverImage = ({ placeholderSrc, src, children, wait = 0, ...rest }: any) => {
    const { onClick } = rest
    const [isHovered, setIsHovered] = useState(false)

    const { run } = useDebounceFn(
        (...arg) => {
            onClick?.(arg)
        },
        {
            wait,
            leading: true,
            trailing: false,
        },
    )

    return (
        <div
            {...rest}
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
            onClick={run}
            style={{
                backgroundImage: `url(${isHovered ? src : placeholderSrc})`,
                backgroundSize: 'container',
                backgroundRepeat: 'no-repeat',
                backgroundPosition: 'center',
            }}
        >
            {typeof children === 'function' ? children(isHovered) : children}
        </div>
    )
}

export default HoverImage
